#!/bin/bash

change_master(){
	master=$1
	master_user=$2
	master_pass=$3
	slave=$4
	slave_user=$5
	slave_pass=$6

	docker exec $slave sh -c "mysql -u"$slave_user" -p"$slave_pass" -e 'stop slave;'"
	master_status=`docker exec $master sh -c 'mysql -u'$master_user' -p'$master_pass' -e "show master status;"'`
	echo $master_status
	master_file=`echo "$master_status" | grep "bin" | awk '{print $1}'`
	echo $master_file
	master_pos=`echo "$master_status" | grep "bin"  | awk '{print $2}'`
	echo $master_pos
	docker exec $slave sh -c "mysql -u"$slave_user" -p"$slave_pass" -e 'change master to master_host="\"$master\"", master_user="\"$master_user\"", master_password="\"$master_pass\"", master_log_file="\"$master_file\"", master_log_pos="$master_pos";'"
	docker exec $slave sh -c "mysql -u"$slave_user" -p"$slave_pass" -e 'start slave;'"
	docker exec $slave sh -c "mysql -u"$slave_user" -p"$slave_pass" -e 'show slave status \G;'"
	check=`docker exec $slave sh -c 'mysql -u'$slave_user' -p'$slave_pass' -e "show slave status \G;" | grep Yes | wc -l'`
	if [ $check == 1 ]; then
	    echo "搭建失败，有错误"
	elif [ $check == 2 ]; then
	    echo "主从搭建成功"
	else
	    echo "数据库错误"
	fi
}

if [ $# == 4 ];then
	change_master $1 $2 $3 $4 $3 $4
elif [ $# == 6 ];then
	change_master $1 $2 $3 $4 $5 $6
else
	echo "参数错误 <master容器名称> <master_user> <master_pass> <slave容器名称> [slave_user] [slave_pass]"
    echo "slave_user和slave_pass不传，默认使用master_user和master_pass"
fi






